#coding=utf-8
import socket
import time
import threading
import pygame

# 颜色
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0, 0, 128)
BLACK = (0, 0, 0)

# 创建连接
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定端口
s.bind(('127.0.0.1',9999))
print('Waiting for connection...')

pygame.init()

# 设置标题
pygame.display.set_caption('UDP视频传输')

# 开启窗口
display_width = 300
display_height = 200
gameDisplay = pygame.display.set_mode((display_width,display_height))

# 判断是否结束pygame
gamefinish = False
# 帧率
frame_rate = 0
# 用于视频显示 delay
clock = pygame.time.Clock()

# 用于帧率计算
start = time.perf_counter()

while not gamefinish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gamefinish = True
        print(event)

    # 无数据接收则线程挂起，等待数据
    data, addr = s.recvfrom(60000)
    frame_rate = frame_rate + 1
    if time.perf_counter() - start > 1:
        start = time.perf_counter()
        frame_rate = 0

    print('Received from %s:%s.' % addr)

    # 字符串再转化为图片
    img = pygame.image.frombuffer(data, (160, 120), "RGB")

    # 窗口内设置白色底色和图片，并更新显示
    gameDisplay.fill(WHITE)
    gameDisplay.blit(img, (0, 0))
    pygame.display.update()

    clock.tick(60)

pygame.quit()

